import { ScrollView, ScrollViewProps, View } from '@tarojs/components';
import NavigationBar from 'components/NavigationBar';
import Placeholder from 'components/Placeholder'
import { useRef } from 'react';
import getSystemInfo from 'utils/getSystemInfo';

export interface ScrollPageViewProps extends ScrollViewProps {
  isBottomPlaceholder?: boolean,
  isHeaderPlaceholder?: boolean,
  children?: any,
  navigation?: {
    title?: string
  },
  onReachEnd?: () => any,
  style?: any,
  navigationBarStyle?: any,
  scrollViewStyle?: any,
}

function ScrollPageView(props: ScrollPageViewProps) {
  const {
    isBottomPlaceholder = false, 
    isHeaderPlaceholder = true, 
    children, 
    navigation = {}, 
    onReachEnd,
    style = {},
    navigationBarStyle = {},
    scrollViewStyle = {},
    ...others
  } = props
  const isReachend = useRef(false)
  const info = getSystemInfo()

  function onScrollHandler(e: any) {
    const {scrollHeight, scrollTop} = e.detail
    if (scrollTop + info.screenHeight + 80 >= scrollHeight) {
      if (!isReachend.current) {
        onReachEnd && onReachEnd()
        isReachend.current = true
      }
    } else {
      if (isReachend.current) {
        isReachend.current = false
      }
    }
  }

  const _scrollViewStyle = {
    height: info.screenHeight - (info.statusBarHeight || 0) - (info.navBarHeight || 0),
    ...scrollViewStyle
  }

  return (
    <View style={style}>
      {navigation.title ? <NavigationBar {...navigation} style={navigationBarStyle} /> : null}
      {isHeaderPlaceholder ? <Placeholder type='wholeNavigationBar' /> : null}
      <ScrollView 
        style={_scrollViewStyle} 
        scrollY 
        onScroll={onScrollHandler}
        {...others}
      >
        {children}
        {isBottomPlaceholder ? <Placeholder type='wholeTabbar' /> : null}
      </ScrollView>
    </View>
  )
}

export default ScrollPageView;
